package com.hhss.qishi.mapper.system.provider;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import com.hhss.qishi.entity.system.Role;

/**
 * 角色
 * sql构造器
 * @author hhss
 * @date 2019年3月31日 
 */
public class RoleProvider{
	
	private static String SQL_ENTITY = "id, uuid, role_name as roleName, role_code as roleCode, description, status,"
			+ " create_user AS createUser, create_time AS createTime, last_update_user AS lastUpdateUser,"
			+ " last_update_time AS lastUpdateTime, create_user AS createUser, last_update_user AS lastUpdateUser";
	
	private static String TABLE_NAME = "sys_role";
	
	/**
	 * 更新角色
	 * 根据id或者uuid
	 * @param role
	 * @return
	 */
	public String updateRoleSQL(final Role role) {
		 return new SQL(){{
			 UPDATE(TABLE_NAME);
			 if(!StringUtils.isEmpty(role.getRoleName())) {
				 SET("role_name = #{role.roleName}");
			 }
			 if(!StringUtils.isEmpty(role.getRoleCode())) {
				 SET("role_code = #{role.roleCode}");
			 }
			 if(!StringUtils.isEmpty(role.getDescription())) {
				 SET("description = #{role.description}");
			 }
			 if(!StringUtils.isEmpty(role.getLastUpdateTime())) {
				 SET("last_update_user = #{role.lastUpdateUser}");
			 }
			 if(!StringUtils.isEmpty(role.getLastUpdateUser())) {
				 SET("last_update_time = #{role.lastUpdateTime}");
			 }
			 WHERE("id = #{role.id} OR uuid = #{role.uuid}");
		 }}.toString();
	}
	
	/**
	 * 查找角色集合
	 * @param role
	 * @return
	 */
	public String getListSQL(final Role role) {
		return new SQL(){{
			 SELECT(SQL_ENTITY);
			 FROM(TABLE_NAME);
			 WHERE("1=1");
			 if(!StringUtils.isEmpty(role.getRoleName())) {
				 AND().WHERE("role_name like CONCAT('%',#{role.roleName},'%')");
			 }
			 if(!StringUtils.isEmpty(role.getDescription())) {
				 AND().WHERE("description like CONCAT('%',#{role.description},'%')");
			 }
			 if(!StringUtils.isEmpty(role.getCreateUser())) {
				 AND().WHERE("create_user = #{role.createUser}");
			 }
			 if(!StringUtils.isEmpty(role.getCreateTime())) {
				 AND().WHERE("create_time = #{role.createTime}");
			 }
			 if(!StringUtils.isEmpty(role.getLastUpdateUser())) {
				 AND().WHERE("last_update_user = #{role.lastUpdateUser}");
			 }
			 if(!StringUtils.isEmpty(role.getLastUpdateTime())) {
				 AND().WHERE("last_update_time = #{role.lastUpdateTime}");
			 }
			 
		 }}.toString();
	}
	
	public String getEntitySQL(final Role role) {
		return new SQL(){{
			SELECT(SQL_ENTITY);
			 FROM(TABLE_NAME);
			 WHERE("1=1");
			 if(!StringUtils.isEmpty(role.getId())) {
				 AND().WHERE("id = #{role.id}");
			 }
			 if(!StringUtils.isEmpty(role.getUuid())) {
				 AND().WHERE("uuid = #{role.uuid}");
			 }
		}}.toString();
	}
	
	public String getListByUserIdSQL(final Long id) {
		return new SQL(){{
			 SELECT(SQL_ENTITY);
			 FROM(TABLE_NAME);
			 WHERE("id IN(SELECT role_id FROM sys_role_user WHERE user_id = #{id})");
		}}.toString();
	}
}
